package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.*
import android.widget.EditText
import android.widget.PopupWindow
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.bp_utils.BpInputValidator

class BpKeyboardPopupWindow(activity: Activity) {
    private val mActivity = activity
    private lateinit var popupWindow: PopupWindow
    private lateinit var replyEdit: EditText
    private var pullListener: OnInputListener? = null

    fun init() {
        val mInflater = LayoutInflater.from(mActivity)
        val editView: View = mInflater.inflate(R.layout.note_popup_window_layout_bg, null)
        popupWindow = PopupWindow(
            editView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.WHITE))
        replyEdit = editView.findViewById<EditText>(R.id.edite_note)
        val sendMsg = editView.findViewById<TextView>(R.id.tv_save)

        popupWindow.isFocusable = true
        popupWindow.isOutsideTouchable = true
        popupWindow.inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED;
        popupWindow.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;

        replyEdit.requestFocus()

        popupWindow.setOnDismissListener {
            BpInputValidator.hideSoftKeyBoard(mActivity)
            val lp = mActivity.window.attributes
            lp.alpha = 1f
            mActivity.window.attributes = lp
            replyEdit.text.clear()
            backgroundAlpha(1f, mActivity)
        }
        sendMsg.setOnClickListener {
            val content: String = replyEdit.text.toString().trim { it <= ' ' }
            pullListener?.onInput(content)
            popupWindow.dismiss()
        }
    }

    fun show(rootView: ConstraintLayout) {
        BpInputValidator.showSoftInput(mActivity,replyEdit)
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0)
        backgroundAlpha(0.7f, mActivity)
    }

    interface OnInputListener {
        fun onInput(inputText: String)
    }

    fun setOnInputListener(listener: OnInputListener) {
        this.pullListener = listener
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     * @param mActivity
     */
    fun backgroundAlpha(bgAlpha: Float, mActivity: Activity) {
        val lp = mActivity.window.attributes
        lp.alpha = bgAlpha //0.0-1.0
        mActivity.window.attributes = lp
    }
}